package com.ruoyi.common.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @title: DocumentUtil
 * @copyright: copyright (c) 2023
 * @author: jiangguanjun
 * @date: 2023/2/18 22:38
 * @firstReview:
 * @lastReview:
 * @desc:
 */
public class DocumentUtil {
    public static Document getDocument(HttpServletRequest request) {
        SAXReader reader = new SAXReader();
        try {
            InputStream ins = request.getInputStream();
            Document doc = reader.read(ins);
            return doc;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, String> docToMap(Document doc) {
        Map<String, String> map = new HashMap<String, String>();
        Element root = doc.getRootElement();
        @SuppressWarnings("unchecked")
        List<Element> list = root.elements();
        for (Element element : list) {
            map.put(element.getName(), element.getText());
        }
        return map;
    }

}
